// @flow
import React from 'react'
import { Select, Button } from 'antd'
import { getSpecs } from 'utils/GeneralOptions'
// import AgGrid from 'components/AgGrid'
import styles from './DeviceTypeEdit.css'
import backBtnStyles from 'styles/commonBackBtn.css'
import Point from 'components/Point'
import VarComp from 'components/VarComp'
import Limits from 'components/Limits'

import DeviceTypeInfoEdit from 'components/DeviceTypeInfoEdit'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {
  form: Object,
  history: Array<any>,
  location: Object
}

const Option = Select.Option

// let pointData = []

type DeviceTypeEditStates = {
  specs: Array<any>,
  types: Array<any>,
  visiblePoint: boolean,
  visibleVariable: boolean,
  pointData: Array<any>,
  varData: Array<any>,
  confirmLoading: boolean,
  syncKmxVisible: boolean,
  deviceTypeInfoVisible: boolean,
  limitsData: Array<Object>
}
class DeviceTypeEdit extends React.Component {
  props: Props
  state: DeviceTypeEditStates
  getPointData: Function
  getVarData: Function
  getPointVars: Function
  getSettingMenu: Function
  handleMenuClick: Function
  closeSyncKmxModal: Function
  closeInfoModal: Function
  editDeviceType: Function
  getLimitsData: Function
  getVarLimits: Function
  goBack: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      specs: [],
      types: [],
      visiblePoint: false,
      visibleVariable: false,
      confirmLoading: false,
      pointData: [],
      varData: [],
      limitsData: [],
      syncKmxVisible: false,
      deviceTypeInfoVisible:false
    }
    this.getPointData = this.getPointData.bind(this)
    this.getVarData = this.getVarData.bind(this)
    this.getPointVars = this.getPointVars.bind(this)
    // this.getSettingMenu = this.getSettingMenu.bind(this)
    // this.handleMenuClick = this.handleMenuClick.bind(this)
    // this.closeSyncKmxModal = this.closeSyncKmxModal.bind(this)
    this.closeInfoModal = this.closeInfoModal.bind(this)
    this.editDeviceType = this.editDeviceType.bind(this)
    this.getLimitsData = this.getLimitsData.bind(this)
    this.getVarLimits = this.getVarLimits.bind(this)
    this.goBack = this.goBack.bind(this)
  }

  goBack = () => {
    history.go(-1)
  }
  getPointData = () => {
    const { recordId } = this.props.location.state
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points?deviceId=${recordId}`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        pointData: json.result
      })
      // pointData = json.result
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  /**
   * [getSpecs description]
   * @param  {[type]} type [description]
   * @return {[type]}      [description]
   */
  getSpecs (type: string) {
    this.setState({
      specs: getSpecs(type).map((d, i) => {
        return <Option key={d.id} value={d.value}>{d.label}</Option>
      })
    })
  }

  /**
   * [handleTypeChange description]
   * @param  {[type]} value [description]
   * @return {[type]}       [description]
   */
  handleTypeChange = (value: string) => {
    this.getSpecs(value)
  }

  getVarData () {
    const { location } = this.props
    const url = `${__SERVICE_API__}device/templates/monitors/variables` +
      `?deviceId=${location.state.recordId}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getPointVars (point: Object) {
    const url = `${__SERVICE_API__}device/templates/monitors/variables` +
      `?monitorPointId=${point.id}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  componentDidMount () {
    this.getPointData()
    this.getVarData()
    this.getLimitsData()
  }

  getLimitsData () {
    const { recordId } = this.props.location.state
    universalFetch(`${__SERVICE_API__}device/templates/monitors/limits?deviceId=${recordId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          limitsData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getVarLimits (data: Object) {
    const { recordId } = this.props.location.state
    universalFetch(`${__SERVICE_API__}device/templates/monitors/limits?deviceId=${recordId}` +
      `&variableId=${data.id}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          limitsData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  // getSettingMenu () {
  //   return <Menu onClick={this.handleMenuClick}>
  //     <Menu.Item key='edit'>编辑</Menu.Item>
  //   </Menu>
  // }
  // <Menu.Item key='kmx'>同步选中设置</Menu.Item>

  // handleMenuClick (menu: Object) {
  //   const { key } = menu
  //   if (key === 'kmx') {
  //     this.setState({
  //       syncKmxVisible: true
  //     })
  //   } else if (key === 'edit') {
  //     this.setState({
  //       deviceTypeInfoVisible: true
  //     })
  //   }
  // }

  editDeviceType () {
    this.setState({
      deviceTypeInfoVisible: true
    })
  }
  closeInfoModal () {
    this.setState({
      deviceTypeInfoVisible: false
    })
  }
  // closeSyncKmxModal () {
  //   this.setState({
  //     syncKmxVisible: false
  //   })
  // }
  render () {
    const { pointData, varData, deviceTypeInfoVisible, limitsData } = this.state
    const { location } = this.props
    const { data } = location.state
    return (
      <div className={styles['main']}>
        <section className={styles['header']}>
          <div className={styles['header-title']}>
            <span>名称: </span>
            <span> {data.name}
            </span>
          </div>
          {/*
            <Button type='danger' style={{ marginLeft: '10px' }}
            onClick={() => this.handleDelete()}>删除</Button>
          */}
          <div className={styles['header-content']}>
            <span>类型: {data.type}</span>
            <span>型号: {data.spec}</span>
          </div>
          <div className={styles['setting']} title='设置'>
            {/* <Dropdown overlay={this.getSettingMenu()}
              trigger={['click']}
              >
              <Icon type='setting' />
            </Dropdown>
            */}

            <DeviceTypeInfoEdit
              {...{
                visible: deviceTypeInfoVisible,
                deviceId: location.state.recordId,
                closeModal: this.closeInfoModal,
                data: data
              }}
              />
          </div>
        </section>
        <Point {...{
          location,
          pointData,
          refreshPoint: this.getPointData,
          getPointVars: this.getPointVars
        }} />
        <VarComp {...{
          location,
          varData,
          pointData,
          refreshVar: this.getVarData,
          refreshLimit: this.getVarLimits
        }} />
        <Limits {...{
          limitsData,
          refreshLimit: this.getLimitsData
        }} />
        <div className={backBtnStyles['goBackBtn']}>
          <Button onClick={this.editDeviceType}>编辑</Button>
          <Button onClick={this.goBack} className={styles['settingBtn']} style={{ marginLeft: '20px' }} >返回</Button>
        </div>
      </div>
    )
  }
}

export default DeviceTypeEdit
